<!--
  文件级注释：我的分账协议页面（平台侧）
  - 展示与当前用户相关的分账协议（参与者/创建者）
  - 支持商户、状态过滤与分页
  - 规则：仅当返回值 code === 0 时认为接口调用成功
-->

<template>
  <div class="container fade-in">
    <div class="header">
      <h2 class="section-title">我的分账协议</h2>
      <div class="actions">
        <button class="btn secondary" @click="resetFilters">
          <span class="icon" v-html="'🔄'"></span>
          重置筛选
        </button>
        <button class="btn primary" @click="fetchList">
          <span class="icon" v-html="'🔍'"></span>
          查询
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid kpi">
      <div class="card kpi slide-up" style="animation-delay: 0.1s">
        <div class="icon" style="background: var(--primary)" v-html="'📋'"></div>
        <div class="meta">
          <div class="label">协议总数</div>
          <div class="value">{{ total }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.2s">
        <div class="icon" style="background: var(--success)" v-html="'✅'"></div>
        <div class="meta">
          <div class="label">启用中</div>
          <div class="value">{{ enabledCount }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.3s">
        <div class="icon" style="background: var(--info)" v-html="'🔥'"></div>
        <div class="meta">
          <div class="label">已激活</div>
          <div class="value">{{ activatedCount }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.4s">
        <div class="icon" style="background: var(--warning)" v-html="'👤'"></div>
        <div class="meta">
          <div class="label">参与角色</div>
          <div class="value">{{ roleCountText }}</div>
        </div>
      </div>
    </div>

    <!-- 筛选器 -->
    <div class="card filters slide-up" style="animation-delay: 0.5s">
      <div class="filter-row">
        <div class="field">
          <label>查询维度</label>
          <div class="checkbox-group">
            <label class="checkbox">
              <input type="checkbox" v-model="filters.IncludeParticipation" />
              <span class="checkmark"></span>
              参与者
            </label>
            <label class="checkbox">
              <input type="checkbox" v-model="filters.IncludeOwned" />
              <span class="checkmark"></span>
              我创建的
            </label>
          </div>
        </div>
        <div class="field">
          <label>商户ID</label>
          <input v-model="filters.MerchantId" class="input" placeholder="输入商户ID（可选）" @keyup.enter="fetchList" />
        </div>
        <div class="field">
          <label>启用状态</label>
          <select v-model.number="filters.EnableStatus" class="input">
            <option :value="-1">全部</option>
            <option :value="1">启用</option>
            <option :value="0">禁用</option>
          </select>
        </div>
        <div class="field">
          <label>激活状态</label>
          <select v-model.number="filters.ActivationStatus" class="input">
            <option :value="-1">全部</option>
            <option :value="1">已激活</option>
            <option :value="0">未激活</option>
          </select>
        </div>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="card slide-up" style="animation-delay: 0.6s">
      <div class="table-header">
        <h3 class="section-title">协议列表</h3>
        <div class="table-actions">
          <button class="btn secondary sm" @click="fetchList">
            <span class="icon" v-html="'🔄'"></span>
            刷新
          </button>
        </div>
      </div>

      <div v-if="loading" class="loading-state">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>

      <div v-else-if="list.length === 0" class="empty-state">
        <div class="empty-icon" v-html="'📋'"></div>
        <h4>暂无分账协议</h4>
        <p>没有找到符合条件的分账协议，请调整筛选条件</p>
      </div>

      <div v-else class="table-container">
        <table class="table">
          <thead>
            <tr>
              <th>协议信息</th>
              <th>关系与比例</th>
              <th>状态</th>
              <th>时间信息</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in list" :key="item.id" class="table-row">
              <td>
                <div class="cell-primary">{{ item.agreementName || '-' }}</div>
                <div class="cell-secondary">{{ item.agreementCode || '-' }}</div>
              </td>
              <td>
                <div class="cell-primary">{{ formatRelation(item.relation) }}</div>
                <div class="cell-secondary">{{ item.myRatio ? `${item.myRatio}%` : '-' }}</div>
              </td>
              <td>
                <div class="status-group">
                  <span :class="['status-badge', item.enableStatus === 1 ? 'success' : 'warning']">
                    {{ formatEnable(item.enableStatus) }}
                  </span>
                  <span :class="['status-badge', item.activationStatus === 1 ? 'info' : 'default']">
                    {{ formatActivation(item.activationStatus) }}
                  </span>
                </div>
              </td>
              <td>
                <div class="cell-primary">{{ formatYMD(item.creationTime) }}</div>
                <div class="cell-secondary">父协议: {{ item.parentAgreementId || '-' }}</div>
              </td>
              <td>
                <router-link class="btn-link" :to="`/divided-agreements/detail/${item.id}`">
                  <span class="icon" v-html="'👁️'"></span>
                  查看详情
                </router-link>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination">
        <button 
          class="btn secondary sm" 
          :disabled="page.Page <= 1"
          @click="onPrev"
        >
          上一页
        </button>
        <span class="page-info">
          第 {{ page.Page }} / {{ totalPages }} 页 (共 {{ total }} 条)
        </span>
        <button 
          class="btn secondary sm" 
          :disabled="page.Page >= totalPages"
          @click="onNext"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { DividedService, type UserRelatedDividedAgreementsRequest } from '../services/divided'
import { isSuccess } from '../services/types'

/** 组件级注释：展示与当前用户相关的分账协议（参与或创建） */

/**
 * 查询筛选参数
 * @returns UserRelatedDividedAgreementsRequest
 */
const filters = ref<UserRelatedDividedAgreementsRequest>({
  IncludeParticipation: true,
  IncludeOwned: true,
  MerchantId: '',
  EnableStatus: -1,
  ActivationStatus: -1,
  OnlySubAgreements: false,
  OnlyMyDetailsWithoutSubAgreement: false,
  Page: 1,
  Limit: 10
})

/** 列表数据 */
const list = ref<any[]>([])
/** 总条数 */
const total = ref(0)
/** 加载状态 */
const loading = ref(false)
/** 分页状态（与 filters 中的 Page/Limit 保持一致） */
const page = computed(() => ({ Page: filters.value.Page ?? 1, Limit: filters.value.Limit ?? 10 }))
/** 总页数 */
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / page.value.Limit)))

/** 启用中的协议数量 */
const enabledCount = computed(() => list.value.filter(item => item.enableStatus === 1).length)
/** 已激活的协议数量 */
const activatedCount = computed(() => list.value.filter(item => item.activationStatus === 1).length)
/** 参与角色统计文本 */
const roleCountText = computed(() => {
  const ownerCount = list.value.filter(item => item.relation === 'Owner').length
  const participantCount = list.value.filter(item => item.relation === 'Participant').length
  if (ownerCount > 0 && participantCount > 0) return '双重角色'
  if (ownerCount > 0) return '创建者'
  if (participantCount > 0) return '参与者'
  return '无角色'
})

/**
 * 函数级注释：获取用户相关的分账协议列表
 * @returns Promise<void>
 * @throws 可能抛出网络异常
 */
async function fetchList(): Promise<void> {
  // 校验至少一个维度被选中
  if (!filters.value.IncludeParticipation && !filters.value.IncludeOwned) {
    alert('至少选择一个维度：参与者或我创建的')
    return
  }
  
  loading.value = true
  try {
    const res = await DividedService.getUserRelatedDividedAgreements(filters.value)
    if (isSuccess(res) && res.data) {
      list.value = res.data.data || []
      total.value = res.data.total || 0
    } else {
      alert(res.message || '获取我的分账协议失败')
    }
  } catch (error) {
    console.error('获取分账协议失败:', error)
    alert('获取分账协议失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

/** 重置筛选条件 */
function resetFilters(): void {
  filters.value = {
    IncludeParticipation: true,
    IncludeOwned: true,
    MerchantId: '',
    EnableStatus: -1,
    ActivationStatus: -1,
    OnlySubAgreements: false,
    OnlyMyDetailsWithoutSubAgreement: false,
    Page: 1,
    Limit: 10
  }
  fetchList()
}

/** 上一页 */
function onPrev(): void {
  if ((filters.value.Page ?? 1) > 1) {
    filters.value.Page = (filters.value.Page ?? 1) - 1
    fetchList()
  }
}

/** 下一页 */
function onNext(): void {
  if ((filters.value.Page ?? 1) < totalPages.value) {
    filters.value.Page = (filters.value.Page ?? 1) + 1
    fetchList()
  }
}

/**
 * 函数级注释：格式化启用状态
 * @param s 启用状态
 * @returns string 文案
 */
function formatEnable(s?: number): string { return s === 1 ? '启用' : s === 0 ? '禁用' : '-' }
/**
 * 函数级注释：格式化激活状态
 * @param s 激活状态
 * @returns string 文案
 */
function formatActivation(s?: number): string { return s === 1 ? '已激活' : s === 0 ? '未激活' : '-' }
/**
 * 函数级注释：格式化关系
 * @param r 关系字符串
 * @returns string 文案
 */
function formatRelation(r?: string): string { return r === 'Owner' ? '我创建的' : r === 'Participant' ? '参与者' : '-' }
/**
 * 函数级注释：格式化日期为 YYYY-MM-DD
 * @param d 日期字符串或 Date
 * @returns string 格式化后的日期；无效或为空返回 '-'
 * @throws 无显式异常（内部容错处理非法日期）
 */
function formatYMD(d?: string | Date | null): string {
  if (!d) return '-'
  const dt = typeof d === 'string' ? new Date(d) : d
  if (isNaN(dt.getTime())) return '-'
  const pad = (n: number) => String(n).padStart(2, '0')
  return `${dt.getFullYear()}-${pad(dt.getMonth() + 1)}-${pad(dt.getDate())}`
}

onMounted(fetchList)
</script>

<style scoped>
/* 整体容器样式 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面头部 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.section-title {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

.actions {
  display: flex;
  gap: 12px;
}

/* 按钮样式 */
.btn {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  text-decoration: none;
  cursor: pointer;
  transition: all 0.2s ease;
}

.btn.primary {
  background: var(--primary);
  color: white;
}

.btn.primary:hover {
  background: var(--primary-dark);
}

.btn.secondary {
  background: var(--bg-secondary);
  color: var(--text-primary);
  border: 1px solid var(--border);
}

.btn.secondary:hover {
  background: var(--bg-tertiary);
}

.btn.sm {
  padding: 6px 12px;
  font-size: 12px;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 统计卡片网格 */
.grid.kpi {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

/* 卡片基础样式 */
.card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--border);
}

/* KPI卡片样式 */
.card.kpi {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 20px;
}

.card.kpi .icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  flex-shrink: 0;
}

.card.kpi .meta .label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 4px;
}

.card.kpi .meta .value {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);
}

/* 筛选器卡片 */
.filters {
  margin-bottom: 24px;
}

.filter-row {
  display: flex;
  gap: 16px;
  align-items: end;
  flex-wrap: wrap;
}

.field {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 200px;
  flex: 1;
}

.field label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
}

/* 输入框样式 */
.input {
  padding: 8px 12px;
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 14px;
  background: white;
  transition: border-color 0.2s ease;
  height: 36px;
}

.input:focus {
  outline: none;
  border-color: var(--primary);
}

/* 复选框组 */
.checkbox-group {
  display: flex;
  gap: 16px;
}

.checkbox {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
}

.checkbox input[type="checkbox"] {
  width: 16px;
  height: 16px;
  cursor: pointer;
}

/* 表格区域 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.table-header .section-title {
  font-size: 18px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.table-container {
  overflow-x: auto;
}

.table {
  width: 100%;
  border-collapse: collapse;
  background: white;
}

.table th {
  background: var(--bg-secondary);
  padding: 12px;
  text-align: left;
  font-weight: 600;
  color: var(--text-primary);
  border-bottom: 2px solid var(--border);
}

.table td {
  padding: 12px;
  border-bottom: 1px solid var(--border);
  vertical-align: top;
}

.table-row:hover {
  background: var(--bg-secondary);
}

/* 单元格内容 */
.cell-primary {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.cell-secondary {
  font-size: 12px;
  color: var(--text-secondary);
}

/* 状态标签 */
.status-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  text-align: center;
  width: fit-content;
}

.status-badge.success {
  background: var(--success-light);
  color: var(--success);
}

.status-badge.warning {
  background: var(--warning-light);
  color: var(--warning);
}

.status-badge.info {
  background: var(--info-light);
  color: var(--info);
}

.status-badge.default {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
}

/* 操作按钮 */
.btn-link {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  color: var(--primary);
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.btn-link:hover {
  background: var(--primary-light);
  color: var(--primary-dark);
}

/* 加载和空状态 */
.loading-state, .empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);
}

.spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top: 3px solid var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  margin-top: 24px;
}

.page-info {
  font-size: 14px;
  color: var(--text-secondary);
}

/* 动画效果 */
.fade-in {
  animation: fadeIn 0.3s ease-out;
}

.slide-up {
  animation: slideUp 0.4s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 16px;
  }
  
  .header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-row {
    flex-direction: column;
  }
  
  .field {
    min-width: auto;
  }
  
  .checkbox-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .grid.kpi {
    grid-template-columns: 1fr;
  }
  
  .pagination {
    flex-direction: column;
    gap: 8px;
  }
  
  .table {
    font-size: 12px;
  }
  
  .table th,
  .table td {
    padding: 8px;
  }
}
</style>
